﻿using Newtonsoft.Json;
using Quartz;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExUtil;
using RuoVea.QuartzNetUI.Server;
using RuoVea.QuartzNetUI.Server.Dto;
using System.Text;
using System.Text.RegularExpressions;

namespace RuoVea.QuartzNetUI.Job
{
    /// <summary>
    /// Http请求Job
    /// </summary>
    [DisallowConcurrentExecution]//不允许此 Job 并发执行任务
    [PersistJobDataAfterExecution]
    public class HttpJob : BaseJob
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tasksQzLogService"></param>
        public HttpJob(ITaskLogService tasksQzLogService) : base(tasksQzLogService) { }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jobData"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public override async Task<RestfulResult> ExecSomethingAsync(TaskDetailInDto jobData)
        {
            RestfulResult restfulResult = new RestfulResult { Code= CodeStatus.BadRequest,Message= jobData.RunType.ToString() };
           
            if (jobData.RunType == RequestTypeEnum.Get)
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    SetHttpClient(httpClient, jobData);
                    HttpResponseMessage httpResponse = await httpClient.GetAsync(jobData?.RequestUrl);
                    //完善返回参数200 
                    restfulResult.Code = httpResponse.StatusCode== System.Net.HttpStatusCode.OK? CodeStatus.OK: CodeStatus.BadRequest;
                    string content =await httpResponse.Content.ReadAsStringAsync();

                    if(content.NotNullOrWhiteSpace()) content = Regex.Unescape(content);
                    if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK)
                        restfulResult.Data = content;
                    else
                        restfulResult.Message = $"StatusCode:{httpResponse.StatusCode},Content:{content}";
                    return restfulResult;
                }
            }
            if (jobData.RunType == RequestTypeEnum.Post)
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    SetHttpClient(httpClient, jobData);
                    if (string.IsNullOrWhiteSpace(jobData?.Parameters))
                        throw new ArgumentNullException("请设置Parameters参数"); 
                    HttpContent? stringContent = new StringContent(jobData.Parameters, Encoding.UTF8, "application/json");
                    HttpResponseMessage httpResponse= await httpClient.PostAsync(jobData.RequestUrl, stringContent);
                    //完善返回参数200 
                    restfulResult.Code = httpResponse.StatusCode == System.Net.HttpStatusCode.OK ? CodeStatus.OK : CodeStatus.BadRequest;
                    string content = await httpResponse.Content?.ReadAsStringAsync();
                    if (content.NotNullOrWhiteSpace()) content = Regex.Unescape(content);

                    if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK)
                        restfulResult.Data = content;
                    else
                        restfulResult.Message = $"StatusCode:{httpResponse.StatusCode},Content:{content}";
                    //完善返回参数200 
                    return restfulResult;
                }
            }
           return restfulResult;
        }

        private void SetHttpClient(HttpClient httpClient, TaskDetailInDto jobData)
        {
            if (!string.IsNullOrWhiteSpace(jobData?.Headers))
            {
                Dictionary<string, string>? headers = JsonConvert.DeserializeObject<Dictionary<string, string>>(jobData.Headers?.Trim());
                foreach (var dic in headers)
                    httpClient.DefaultRequestHeaders.Add(dic.Key, dic.Value);
            }
        }
    }
}
